﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        //define value
        private long numFileDel = 0;
        private long numFileNotDel = 0;
        private Stopwatch sw = new Stopwatch();
        private TimeSpan elapsedTime = new TimeSpan();
        private Thread myThread;
        private bool IsFolderExit = true;

        public Form1()
        {
            InitializeComponent();
            btnStop.Enabled = false;
        }

        /// <summary>
        /// Method when user click Brower button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrower_Click(object sender, EventArgs e)
        {
            folderBrowserDialogDelete.ShowDialog();
            txtPath.Text = folderBrowserDialogDelete.SelectedPath.ToString();
        }

        /// <summary>
        /// Method when user click Select Directory menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void selectDirectoryMenu_Click(object sender, EventArgs e)
        {
            folderBrowserDialogDelete.ShowDialog();
            txtPath.Text = folderBrowserDialogDelete.SelectedPath.ToString();
        }

        /// <summary>
        /// Method when user click Exit menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitMenu_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// Method when user click Help File menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void helpFileMenu_Click(object sender, EventArgs e)
        {
            Process.Start("WINWORD.exe", "D:\\Help.docx");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void aboutMenu_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Delete Folder Tool v01.00" + Environment.NewLine
                                + Environment.NewLine + "Created by ThanhDQ6", "About");
        }

        /// <summary>
        /// Method when user click Delete button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            #region normal
            ////Set status of button when start delete process
            //btnStop.Enabled = true;
            //btnDelete.Enabled = false;
            ////Preset value
            //numFileDel = 0;
            //numFileNotDel = 0;
            //sw.Reset();

            //try
            //{
            //    dir = new DirectoryInfo(@txtPath.Text);

            //    if (dir.Exists)
            //    {
            //        //Start timmer
            //        sw.Start();
            //        //Execute proccess delete
            //        DeleteFolder(dir);
            //        //Stop timer
            //        sw.Stop();
            //        //Get timer
            //        elapsedTime = sw.Elapsed;
            //        //Show result
            //        this.lblResult.Text = "(" + numFileDel.ToString() + ") Files Deleted Successfully. "
            //                            + "(" + numFileNotDel.ToString() + ") Files Failed Deletion"
            //                            + "Deleted time is: " + elapsedTime.ToString();
            //        //Set status of button when finish delete process
            //        btnStop.Enabled = false;
            //        btnDelete.Enabled = true;
            //    }
            //    else
            //    {
            //        MessageBox.Show("Directory does not exit!");
            //    }
            //}
            //catch (System.ArgumentException)
            //{

            //    MessageBox.Show("Directory does not exit!");
            //}
            #endregion

            #region thread
            //Create new thread
            myThread = new Thread(new ThreadStart(this.CallThreadDelete));
            myThread.IsBackground = true;
            myThread.Priority = ThreadPriority.Lowest;

            //Set status of button when start delete process
            btnStop.Enabled = true;
            btnDelete.Enabled = false;

            //Preset value
            numFileDel = 0;
            numFileNotDel = 0;
            sw.Reset();

            //Call thread execute      
            myThread.Start();

            //Wait until thread finish
            myThread.Join();

            //Get timer and show result
            elapsedTime = sw.Elapsed;
            if (IsFolderExit)
            {
                lblResult.Text = "(" + numFileDel.ToString() + ") Files Deleted Successfully. "
                                    + "(" + numFileNotDel.ToString() + ") Files Failed Deletion"
                                    + "Deleted time is:" + elapsedTime.ToString();
            }
            else
            {
                txtPath.Text = "";
                lblResult.Text = "";
            }
            //Set status of button when finish delete process
            btnStop.Enabled = false;
            btnDelete.Enabled = true; 
            #endregion
        }

        /// <summary>
        /// Method when user click stop button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            myThread.Abort();
        }

        /// <summary>
        /// Method is call thread
        /// </summary>
        private void CallThreadDelete()
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(@txtPath.Text);

                if (dir.Exists)
                {
                    //Start timmer
                    sw.Start();
                    //Execute proccess delete
                    DeleteFolder(dir);
                    //Stop timer
                    sw.Stop();
                    myThread.Abort();
                }
                else
                {
                    MessageBox.Show("Directory does not exit!");
                    IsFolderExit = false;
                }
            }
            catch (System.ArgumentException)
            {

                MessageBox.Show("Directory does not exit!");
                IsFolderExit = false;
            }
        }

        /// <summary>
        /// Method delete folder and file using recursion
        /// </summary>
        /// <param name="directoryInfo">Path of directory is deleted</param>
        private void DeleteFolder(DirectoryInfo directoryInfo)
        {
            //Delete all file in folder
            foreach (FileInfo file in directoryInfo.GetFiles())
            {
                try
                {
                    File.SetAttributes(file.FullName, FileAttributes.Normal);
                    file.Delete();
                    this.numFileDel++;
                    Thread.Sleep(5);
                }
                catch (System.UnauthorizedAccessException)
                {
                    this.numFileNotDel++;
                    continue;
                }
            }

            //Recurse to sub folder
            foreach (DirectoryInfo subFolder in directoryInfo.GetDirectories())
            {
                DeleteFolder(subFolder);
                Thread.Sleep(5);
            }

            //Delete folder if  it empty
            try
            {
                directoryInfo.Delete();
            }
            catch (System.IO.IOException)
            {
                return;
            }
        }
    }
}
